import sys
import termios
import fcntl
import select
import time

class NonBlockingKeyDetect:
    def __enter__(self):
        self.old_settings = termios.tcgetattr(sys.stdin)
        new_settings = termios.tcgetattr(sys.stdin)
        new_settings[3] &= ~(termios.ECHO | termios.ICANON)  # 禁用回显和规范模式
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, new_settings)
        return self

    def __exit__(self, *args):
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)

    def read_key(self):
        if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
            return sys.stdin.read(1)
        return None

# 使用示例
if __name__ == "__main__":
    try:
        with NonBlockingKeyDetect() as key_detector:
            print("Press 'a' to test, 'q' to quit")
            while True:
                key = key_detector.read_key()
                if key is not None:
                    print(key)
                # else:
                #     print('No key pressed')

                # 在此处添加其他程序逻辑
                # time.sleep(0.05)  # 控制检测频率
    except KeyboardInterrupt:
        pass